package com.lyx.question.config;

/**
 * @author 14667
 * @date 2022/7/19 9:27
 */


import com.lyx.common.exception.BusinessException;
import com.lyx.common.exception.ErrorUtil;
import com.lyx.common.exception.ExceptionEnum;
import com.lyx.common.result.R;
import com.lyx.common.result.Result;
import com.lyx.common.result.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * RestControllerAdvice，统一异常处理
 * @author 14667
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.lyx.question.controller")
public class ExceptionHandlerConfig {

    /**
     * 业务异常处理
     *
     * @param e 业务异常
     * @return
     */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
    public R exceptionHandler(BusinessException e) {
        log.error(ErrorUtil.errorInfoToString(e));
        return R.error().message(e.getErrorMsg()).code(e.getCode());
    }

    /**
     * 参数异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    @ResponseBody
    public R handValidException(MethodArgumentNotValidException e) {
        log.error("数据校验异常:{}，异常类型：{}", e.getMessage(), e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, Object > errorMap = new HashMap<>();
        bindingResult.getFieldErrors().forEach(item -> {
            // 获取验证不通过字段名
            String field = item.getField();
            // 获取验证不通过字段信息
            String message = item.getDefaultMessage();
            errorMap.put(field, message);
        });
        return R.error().message(ExceptionEnum.DATA_CHECK_FAIL.getMsg()).code(ExceptionEnum.DATA_CHECK_FAIL.getCode()).data(errorMap);
    }
    /**
     * 未知异常处理
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e) {
        // 把错误信息输入到日志中
        log.error(ErrorUtil.errorInfoToString(e));
        return ResultUtil.error(ExceptionEnum.UNKNOWN.getCode(),
                ExceptionEnum.UNKNOWN.getMsg());
    }



    /**
     * 空指针异常
     */
    @ExceptionHandler(value = NullPointerException.class)
    @ResponseBody
    public Result exceptionHandler(NullPointerException e) {
        log.error(ErrorUtil.errorInfoToString(e));
        return ResultUtil.error(ExceptionEnum.INTERNAL_SERVER_ERROR.getCode(),
                ExceptionEnum.INTERNAL_SERVER_ERROR.getMsg());
    }
}

